$(document).ready(function () {

    layui.use(function () {

        var layer = layui.layer;

        laydate = layui.laydate;
        table = layui.table;

        // 表格
        form = layui.form;
        form.on('select(type-select)', function (data) {
            $('div[lay-filter="search"]').click();
        });
        form.on('select(status-select)', function (data) {
            $('div[lay-filter="search"]').click();
        });
        form.on('select(save-type)', function (data) {

            var value = data.value;

            $('#item-floor').hide()
            $('#item-weight').hide()

            if (value == 1 || value == 2 || value == 6) {
                $('#item-floor').show()
            } else if (value == 4) {
                $('#item-weight').show()
            }

        });

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            var d = data.field
            var paramsSave = {}

            paramsSave.seqNo = d.seqNo;
            paramsSave.name = d.name;
            paramsSave.type = d.type;

            if (d.type == 1 || d.type == 2 || d.type == 6) {
                paramsSave.floor = d.floor;
            }

            if (d.type == 4) {
                paramsSave.weight = d.weight;
            }
            saveProgram(paramsSave)

            return false;
        });

        initSubMenu();
        queryTable();
        queryDevice()

    });
})
var params = {};//查询条件参数
var form, unit, laydate, table;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID

var deviceArr = [];

// 查询表格数据
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 240
    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/train/project/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , css: [
                '.layui-table-view td[data-edit]{color: rgb(28, 214, 234);}'
            ].join('')
            , cols: [[ //标题栏
                { field: 'seqNo', title: '排序', align: "center", edit: 'editable' }
                , { field: 'name', title: '项目名称', align: "center", edit: 'editable' }
                , { field: 'typeDesc', title: '项目类型', align: "center" }
                , {
                    field: 'floor', title: '楼层', align: "center", edit:
                        function (d) {
                            if (d.type == 1 || d.type == 2 || d.type == 6) {
                                return 'text';
                            }
                        }
                    , templet: function (d) {
                        return d.floor || '-';
                    }
                }
                , {
                    field: 'weight', title: '负重(千克)', align: "center", edit:
                        function (d) {
                            if (d.type == 4) {
                                return 'text';
                            }
                        }
                    , templet: function (d) {
                        return d.weight || '-';
                    }
                }
                , { field: 'statusDesc', title: '当前状态', align: "center" }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool" >
                                    <div onclick='queryNodeList("${d.id}")' class="table-record layui-btn">
                                        <img src="../static/img/del.png">环节配置
                                    </div>
                                    <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                                        <img src="../static/img/del.png">删除
                                    </div>
                                </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

        table.on('edit(table)', function (obj) {

            var value = obj.value // 得到修改后的值

            var data = obj.data // 得到所在行所有键值

            if (value.replace(/\s/g, '') === '') {

                layer.tips('值不能为空', this, { tips: 1, time: 800 });

                return obj.reedit();

            }
            saveProgram(data)

        });
    });
}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/train/project/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openDrawer(1)
            break;


        default:
            break;
    }
}



openDrawer = (type, res) => {
    drawer = layer.open({
        title: (type == 1 ? "新增" : "编辑") + '项目',
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['30%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {
            if (res) {
                form.val('editForm', res);

            } else {
                form.render(null, 'editForm');
            }
        },
        content: `<form class="layui-form layui-form-pane" id="add-form"  lay-filter="editForm"  action="">
                    <div class="form-item">
                        <label class="layui-form-label">排序</label>
                        <div class="layui-input-block">
                            <input type="text" name="seqNo" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">项目名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-affix="clear" placeholder="请输入" lay-verify="required"
                                class="layui-input">
                        </div>
                    </div>
                   <div class="form-item">
                        <label class="layui-form-label">项目类型</label>
                        <div class="layui-input-block">
                            <select name="type" lay-filter="save-type" lay-verify="required">
                               ${new ST().project()}
                            </select>
                        </div>
                    </div>
                    <div class="form-item" id="item-weight" style="display:none;">
                        <label class="layui-form-label">负重重量(千克)</label>
                        <div class="layui-input-block">
                            <input type="text" name="weight"  lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item" id="item-floor" style="display:none;">
                        <label class="layui-form-label">楼层层数</label>
                        <div class="layui-input-block">
                            <input type="text" name="floor" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool" >
                        <button type="reset" class="layui-btn layui-btn-primary btn-reset">重置</button>
                        <button class="layui-btn" lay-submit lay-filter="edit">确认</button>
                    </div>
                </form>`
    });

}



// 保存节点信息接口
saveProgram = (params) => {


    new AjaxChain()
        .setUrl('/train/project/save')
        .setMethod('post')
        .setData(JSON.stringify(params))
        .then(data => {
            layer.close(drawer);
            layer.msg('保存成功', { icon: 1, time: 2000 });
            queryTable()
        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}




// 环节节点弹窗列表
queryNodeList = (id) => {

    layer.open({
        title: `<div style="height: 100%;display: flex;align-items: center;">
                    <div class="table-edit layui-btn" onclick=addNewNodes("${id}",1)> 
                        <img src="../static/img/report.png">新增环节
                    </div>
                </div>`,
        maxmin: true,
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['60%', '100%'],
        shade: 0.3,
        shadeClose: false,
        move: false,
        id: 'rd-offset',
        full: function () {

            table.resize('node-table');

        },
        restore: function () {

            table.resize('node-table');

        },
        success: function (layero, index, that) {

            queryNodeTable(id)
        },
        content: ` <table id="node-table" lay-filter="node-table"></table>`
    });

}

//新增环节弹窗
addNewNodes = (id, type) => {

    layer.open({
        type: 1,
        area: '40%',
        offset: ['20%'],
        resize: false,
        shadeClose: true,
        title: type == 1 ? "新增" : "编辑" + '节点',
        content: `<form class="layui-form layui-form-pane" id="node-form" lay-filter="nodeForm" action="">
                    <div class="form-item">
                        <label class="layui-form-label">环节</label>
                        <div class="layui-input-block">
                         <select name="seqNo" lay-verify="required">
                               ${new ST().projectNode()}
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">环节名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-affix="clear" lay-verify="required" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">绑定设备</label>
                        <div class="layui-input-block">
                            <select name="deviceId" lay-verify="required" lay-search="{fuzzy: true}">
                                ${deviceArr.reduce((x, y) => {
            return x + `<option value="${y.id}" }>${y.name}（${y.code}）</option>`
        }, '<option value="">可搜索名称或设备号</option>')}
                             </select>
                        </div>
                    </div>
                    <div class="form-item pane-tool">
                        <div class="layui-btn layui-edit-submit" lay-submit  lay-filter="node-edit">确认</div>
                    </div>
                </form>`,
        success: function (layero, index, that) {
            form.render();

            // form.val('nodeForm', res);

            form.on('submit(node-edit)', function (data) {
                var field = data.field;

                field.projectId = id;

                saveNode(field, index)

                return false;
            });
        },
    });

}



// 加载环节列表
queryNodeTable = (id) => {
    let toolWidth = window.innerWidth / 1920 * 120
    table.render({
        elem: '#node-table'
        , text: {
            none: '暂无数据'
        }
        , method: 'get'
        , url: ajaxPrefix() + "/train/project/node/list"
        , headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        }
        , where: {
            projectId: id,
        }
        , parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.status == 200 ? 0 : 1, //解析接口状态
                "msg": res.message, //解析提示文本
                "data": res.result
            };
        }
        , request: {
            pageName: 'pageNum' //页码的参数名称，默认：page
            ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
        }
        // ,css: [

        //     '.layui-table-view td[data-edit]{color: #16B777;}'
        //   ].join('')
        , cols: [[ //标题栏
            { field: 'name', title: '环节名称', align: "center", edit: 'editable' },
            {
                field: 'seqNo', title: '环节', align: 'center', minWidth: 200
                , unresize: true, align: 'center', templet: function (d) {

                    var seqStr = new ST().projectNode(1).reduce((x, y) => {
                        return x + `<option value="${y.type}" ${(y.type == d.seqNo) ? 'selected' : ''}>${y.name}</option>`
                    }, '<option value="">环节</option>')

                    return `<select name="seqNo" lay-filter="select-seqNo"  lay-append-to="body">
                                ${seqStr}
                            </select> `
                }
            },
            {
                field: 'deviceId', title: '绑定设备', align: 'center', minWidth: 300
                , unresize: true, align: 'center', templet: function (d) {
                    var deviceStr = deviceArr.reduce((x, y) => {
                        return x + `<option value="${y.id}" ${(y.id == d.deviceId) ? 'selected' : ''}>${y.name}（${y.code}）</option>`
                    }, '<option value="">可搜索名称或设备号</option>')

                    return `<select name="deviceId" lay-search="{fuzzy: true}" lay-filter="select-device"  lay-append-to="body">
                                ${deviceStr}
                            </select> `
                }
            }
            , {
                title: '操作',
                align: 'center',
                width: toolWidth,
                toolbar: '#table-node-tool',
            },
        ]]
        , height: 'full'
        // ,skin: 'line' //表格风格
        , even: true
        , page: false
        , done: function (res, curr, count) {
            var options = this;
            // 获取当前行数据 - 自定义方法
            table.getRowData = function (tableId, elem) {
                var index = $(elem).closest('tr').data('index');
                return table.cache[tableId][index] || {};
            };

            form.render()

            form.on('select(select-device)', function (obj) {

                var data = table.getRowData(options.id, obj.elem);

                if (obj.value == data.deviceId) {
                    return
                } else {
                    data.deviceId = obj.value
                    saveNode(data);
                }

            });
            form.on('select(select-seqNo)', function (obj) {

                var data = table.getRowData(options.id, obj.elem);

                if (obj.value == data.seqNo) {
                    return
                } else {
                    data.seqNo = obj.value
                    saveNode(data);
                }

            });



            // 单元格编辑事件

            table.on('edit(node-table)', function (obj) {

                var value = obj.value // 得到修改后的值

                var data = obj.data // 得到所在行所有键值

                if (value.replace(/\s/g, '') === '') {

                    layer.tips('值不能为空', this, { tips: 1, time: 800 });

                    return obj.reedit();

                }
                saveNode(data)

            });

        }

    });
    // 行工具事件
    table.on('tool(node-table)', function (obj) {
        var that = this;
        var res = obj.data;

        var type = parseInt(obj.event);
        if (type == 3) {//删除
            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/train/project/node/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryNodeTable(res.projectId)
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });

        }
    });

}



// 保存环节信息接口
saveNode = (params, index) => {
    new AjaxChain()
        .setUrl('/train/project/node/save')
        .setMethod('post')
        .setData(JSON.stringify(
            params
        ))
        .then(data => {
            if (index) {
                layer.close(index);
            }

            layer.msg('配置成功', { icon: 1, time: 2000 });
            queryNodeTable(params.projectId)
        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}




// 查询所有设备
queryDevice = () => {

    new AjaxChain()
        .setUrl('/device/train/select')
        .then(data => {
            deviceArr = data
        })
        .send();
}